//
//  AppDelegate.m
//  YouSheng
//
//  Created by aaa on 16/8/17.
//  Copyright © 2016年 FanShuHan. All rights reserved.
//

#import "AppDelegate.h"
#import "YSMainTabBarController.h"
#import "YSAppConfig.h"
#import "YSLoginManager.h"
#import "YSService.h"
#import "YSLoginViewController.h"


static NSString * const YSNotificationLogout = @"YSNotificationLogout";
@interface AppDelegate () <NIMLoginManagerDelegate>
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSString *appKey =  [YSAppConfig sharedConfig].appKey;
    NSString *cerName = [YSAppConfig sharedConfig].cerName;
    
    // 初始化SDK
    [[NIMSDK sharedSDK] registerWithAppID:appKey
                                  cerName:cerName];
    
    [self registerAPNs];
    
    [self commonInitListenEvents];
    
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor darkGrayColor];
    [self.window makeKeyAndVisible];
    
    [self setupMainViewController];
    return YES;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NIMSDK sharedSDK].loginManager removeDelegate:self];
}

#pragma mark - ApplicationDelegate
- (void)applicationWillResignActive:(UIApplication *)application {
    
}

/**
 *  App进入后台，显示未读信息数量
 *
 */
- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSInteger count = [[[NIMSDK sharedSDK] conversationManager] allUnreadCount];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

/**
 *  成功注册APNS
 *
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken];
    YSLog(@"didRegisterForRemoteNotificationsWithDeviceToken:  %@", deviceToken);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    YSLog(@"receive remote notification:  %@", userInfo);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    YSLog(@"fail to get apns token :%@",error);
    
}

- (void)setupMainViewController {
    LoginData *data = [[YSLoginManager sharedManager] currentLoginData];
    NSString *account = [data account];
    NSString *token = [data token];
    //如果有缓存用户名密码推荐使用自动登录
    if ([account length] && [token length]) {
        [[[NIMSDK sharedSDK] loginManager] autoLogin:account
                                               token:token];
        [[YSServiceManager sharedManager] start];
        YSMainTabBarController *main = [[YSMainTabBarController alloc] initWithNibName:nil bundle:nil];
        self.window.rootViewController = main;
    } else {
        [self setupLoginViewController];
    }
}

- (void)setupLoginViewController {
    YSLoginViewController *loginController = [[YSLoginViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginController];
    self.window.rootViewController = nav;
}
#pragma mark - 注销通知
- (void)commonInitListenEvents {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(logout:)
                                                 name:YSNotificationLogout
                                               object:nil];
    [[[NIMSDK sharedSDK] loginManager] addDelegate:self];
}
#pragma mark - misc
- (void)registerAPNs {
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)])
    {
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}

#pragma mark - 注销
-(void)logout:(NSNotification*)note {
    
    [self doLogout];
}

- (void)doLogout {
    
    [[YSLoginManager sharedManager] setCurrentLoginData:nil];
    [[YSServiceManager sharedManager] destory];
}

#pragma NIMLoginManagerDelegate
-(void)onKick:(NIMKickReason)code clientType:(NIMLoginClientType)clientType {
    
}

- (void)onAutoLoginFailed:(NSError *)error {
    //只有连接发生严重错误才会走这个回调，在这个回调里应该登出，返回界面等待用户手动重新登录。
}
@end
